package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.CryptoUtil;
import com.zhongkai.app.service.AppGuardService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class AppGuardServiceImpl implements AppGuardService {

    @Autowired
    private IBaseDao iBaseDao;


    /**
     * APP维修用户列表
     */
    @Override
    public ZhongkaiResult guardList() {

        List list = iBaseDao.find("from Guard");
        return ZhongkaiResult.ok(list);
    }


    /**
     * APP为设备绑定用户
     *
     * @param unit_uuid   设备uuid
     * @param user_name   用户姓名
     * @param user_phone  用户手机号
     * @param user_number 身份证号
     * @param sex         性别 1男 2女
     * @param longitude   经度
     * @param latitude    纬度
     * @param province    省
     * @param city        市
     * @param country     区
     * @param town        乡镇
     * @param address     详细地址
     * @param ope_user    操作人员姓名
     * @param ope_uuid    操作人员uuid
     * @param pact_num    合同编号
     * @param set_vol_uuid  大客户uuid 传0代表没有
     * @param set_alias  设备别名
     * */

    @Override
    public ZhongkaiResult guardBoundUser(String unit_uuid, String user_name, String user_phone, String user_number, String sex, String longitude, String latitude, String province, String city, String country, String town, String address, String ope_user, String ope_uuid, String pact_num, String set_vol_uuid, String set_alias) {
        if (StringUtils.isNullOrEmpty(unit_uuid) || StringUtils.isNullOrEmpty(user_name)
                || StringUtils.isNullOrEmpty(user_phone) || StringUtils.isNullOrEmpty(user_number)
                || StringUtils.isNullOrEmpty(longitude) || StringUtils.isNullOrEmpty(latitude)
                || StringUtils.isNullOrEmpty(province) || StringUtils.isNullOrEmpty(city)
                || StringUtils.isNullOrEmpty(country) || StringUtils.isNullOrEmpty(address) || StringUtils.isNullOrEmpty(pact_num)
                || StringUtils.isNullOrEmpty(set_vol_uuid) || StringUtils.isNullOrEmpty(set_alias)


                ) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'"); //验证设备

        if (setUnit == null) {
            return ZhongkaiResult.build(500, "设备不存在");
        } else if ("2".equals(setUnit.getSetRemove())) {
            return ZhongkaiResult.build(500, "设备已被删除");
        } else if ("2".equals(setUnit.getSetBound())) {
            return ZhongkaiResult.build(500, "该设备已绑定过用户");
        }


        // setUnit.setApp
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser au where au.appPhone='" + user_phone + "'"); //查询客户是否存在


        //验证地址
        Province province1 = (Province) iBaseDao.get("from Province pr where pr.provinceId='" + province + "'");

        City city1 = (City) iBaseDao.get("from City pr where pr.cityId='" + city + "'");

        Country country1 = (Country) iBaseDao.get("from Country pr where pr.countryId='" + country + "'");


        if (province1 == null || city1 == null || country1 == null) {
            return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
        }
        String address_all = "";

        if ("1".equals(town) || StringUtils.isNullOrEmpty(town)) {
            address_all = province1.getName() + city1.getName() + country1.getName() + address;

        } else {
            Town town1 = (Town) iBaseDao.get("from Town pr where pr.townId='" + town + "'");
            if (town1 == null) {
                return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
            }

            address_all = province1.getName() + city1.getName() + country1.getName() + town1.getName() + address;
        }

/*        if (town1 == null) {
            address_all = province1.getName() + city1.getName() + country1.getName() + address;

        } else {
            address_all = province1.getName() + city1.getName() + country1.getName() + town1.getName() + address;
        }*/


        if ("0".equals(set_vol_uuid)) {
            setUnit.setSetVolName("无");
            setUnit.setSetVolUuid("无");
        }else {
            Chinaset chinaset = (Chinaset) iBaseDao.get("from Chinaset se where se.uuid='" + set_vol_uuid + "'");
            if (chinaset == null) {
                return ZhongkaiResult.build(500, "该大客户不存在");
            } else {
                setUnit.setSetVolName(chinaset.getSetName());
                setUnit.setSetVolUuid(set_vol_uuid);
            }
        }

        String uuid;

        long millis = new DateTime().getMillis(); //获取当前系统时间戳


        if (appUser == null) {

            appUser = new AppUser();


            uuid = TTHelp.generate();
            appUser.setAppUuid(uuid);
            appUser.setAppName(user_name);
            appUser.setAppPhone(user_phone);
            appUser.setUserNumber(user_number); //身份证号

            appUser.setAppVice("户主用户");
            appUser.setAppViceId(3);

            //加密
            try {
                String pass = CryptoUtil.encode64(CryptoUtil.SALT, "123456");

                //设置加密后的密码
                appUser.setAppPassword(pass);
            } catch (Exception e) {
                e.printStackTrace();
                return ZhongkaiResult.build(400, "数据加密失败");
            }


            appUser.setAppAddress(address);
            appUser.setAppProvince(province);
            appUser.setAppCity(city);
            appUser.setAppCountry(country);


            appUser.setAppTime(millis);
            appUser.setAppRemove("1");
            appUser.setAppSex(sex);

            appUser.setAppImg("http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg");
            appUser.setAddress_all(address_all);

            iBaseDao.save(appUser);
        } else {

            uuid = appUser.getAppUuid();
            appUser.setAppName(user_name); //更新姓名
            appUser.setUserNumber(user_number); //身份证号

            appUser.setAppVice("户主用户"); //用户权限
            appUser.setAppViceId(3);


            // appUser.setAppAddress(address);
            // appUser.setAppProvince(province);
            // appUser.setAppCity(city);
            //appUser.setAppCountry(country);

/*            if (!StringUtils.isNullOrEmpty(town)) {
                appUser.setAppTown(town);
            }*/


            appUser.setAppMoTime(millis); //时间
            appUser.setAppRemove("1"); //非删除状态
            appUser.setAppSex(sex); //性别


            //appUser.setAddress_all(address_all);


            iBaseDao.update(appUser);
        }
//...................................................................
        AppRole appRole = (AppRole) iBaseDao.get("from AppRole su where su.roleName='户主用户'");

        if (appRole == null) {
            return ZhongkaiResult.build(500, "户主权限缺失,请联系管理员");
        }
        FsonUser fsonUser = new FsonUser();//父子关系表
        fsonUser.setfUid(setUnit.getSetUuid()); //可操控设备的uuid
        fsonUser.setAppPhone(user_phone); //用户手机号
        fsonUser.setFatherPhone("0");//父用户手机号如果是户主用户存入0
        fsonUser.setAppRole(appRole.getId());//角色id
        fsonUser.setAppUuid(uuid);//可操控设备用户的唯一标识
        fsonUser.setfUuid("0");//父用户的唯一标识户主存入0
        fsonUser.setSetAlias(set_alias);//设备别名
        iBaseDao.save(fsonUser);
//...................................................................

        setUnit.setUserUuid(uuid);
        setUnit.setUserPhone(user_phone);
        setUnit.setUserName(user_name);
        setUnit.setSetBound("2");

        setUnit.setLongitude(longitude);
        setUnit.setLatitude(latitude);

        setUnit.setAppAddress(address);
        setUnit.setAppProvince(province);
        setUnit.setAppCity(city);
        setUnit.setAppCountry(country);

        if (!StringUtils.isNullOrEmpty(town)) {
            setUnit.setAppTown(town);
        }


        setUnit.setAppAddressAll(address_all);

        setUnit.setOpeUuid(ope_uuid); //录入人员uuid
        setUnit.setOpeUser(ope_user); //录入人员昵称

        setUnit.setPactNumber(pact_num);//合同编号
        //setUnit.setPactNumber(pact_number);

        setUnit.setSetAlias(set_alias); //设备别名

        iBaseDao.update(setUnit);

        return ZhongkaiResult.ok();
    }


    /**
     * 获取大客户列表
     * */
    @Override
    public ZhongkaiResult getBigUserList() {
        SetRole setRole = (SetRole) iBaseDao.get("from SetRole sr where sr.name='大客户'");

        if (setRole == null) {

            return ZhongkaiResult.build(500, "大客户角色不存在");
        }
        //Chinaset"setRole", setRole.getId()
        //  Chinaset
        List list = iBaseDao.find("from Chinaset ca where ca.setRole=" + setRole.getId());
        return ZhongkaiResult.ok(list);
    }
}
